<template>
  <div class="create-reset">
    <div class="item">
      <!-- <div>
        <van-nav-bar
          title="创建预约"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
        />
      </div> -->
      <div class="resetButton">
        <van-icon name="manager-o" />
        <span class="text">{{ this.$route.query.username }}</span>
        <span class="text">{{ driver }}</span>
        <div class="isfail">{{ execNum }}</div>
      </div>
      <div class="info">
        <van-form
          @submit="onSubmit"
          validate-trigger="onSubmit"
          ref="form"
          :v-model="form"
          :show-error="false"
          label-width="70px"
        >
          <div class="box1">
            <div class="title"><span>基本信息</span><span>(必填)</span></div>
            <van-field
              v-model.trim="form.driverName"
              name="driverName"
              label="姓名"
              placeholder="请输入姓名"
              autocomplete="off"
            />
            <van-field
              label="车牌号"
              name="carNumber"
              v-model.trim="form.carNumber"
            >
              <template #input>
                <car-plate-keyboard @submit="carSubmit"></car-plate-keyboard>
                <!-- <car-plate-keyboard @input="onPlateNumberInput"></car-plate-keyboard> -->
              </template>
            </van-field>
            <!-- <van-cell title="车牌号">
            <template #right-icon>
              <car-plate-keyboard @submit="submit"></car-plate-keyboard>
            </template>
          </van-cell> -->
            <van-field
              v-model.trim="form.sendOrder"
              name="sendOrder"
              label="送货单数"
              @focus="preKey"
              @touchstart.native.stop="sendOrderKeyBorad = true"
              placeholder="请输入送货单数"
              autocomplete="off"
            />
            <van-number-keyboard
              v-model="form.sendOrder"
              :show="sendOrderKeyBorad"
              :maxlength="6"
              @blur="handleSendOrderKeyBorad"
            />
            <van-field
              v-model.trim="form.sendCount"
              name="sendCount"
              label="送货件数"
              @focus="preKey"
              @touchstart.native.stop="showKeyBorad = true"
              placeholder="请输入送货件数"
              autocomplete="off"
            />
            <!-- @blur="showKeyBorad = false" -->
            <van-number-keyboard
              v-model="form.sendCount"
              :show="showKeyBorad"
              :maxlength="6"
              @blur="handleshowKeyBorad"
            />
            <van-field
              name="sendChannel"
              v-model.trim="form.sendChannel"
              label="送货渠道"
              @focus="preKey"
              placeholder="请点击选择"
              autocomplete="off"
              @click="sendChannelPicker = true"
            />
            <van-popup v-model="sendChannelPicker" position="bottom">
              <van-picker
                show-toolbar
                value-key="label"
                :columns="sendChannelColumns"
                @confirm="sendChannelConfirm"
                @cancel="sendChannelPicker = false"
              >
              </van-picker>
            </van-popup>
            <van-field
              v-if="sendChannelValue == '1'"
              name="logisticsType"
              v-model.trim="form.logisticsType"
              label="物流类型"
              @focus="preKey"
              placeholder="请点击选择"
              autocomplete="off"
              @click="logisticsTypePicker = true"
            />
            <van-popup v-model="logisticsTypePicker" position="bottom">
              <van-picker
                show-toolbar
                value-key="label"
                :columns="logisticsColumns"
                @confirm="logisticsConfirm"
                @cancel="logisticsTypePicker = false"
              >
              </van-picker>
            </van-popup>
            <van-field
              name="sendDate"
              v-model.trim="form.sendDate"
              label="预约日期"
              @focus="preKey"
              placeholder="点击选择日期"
              autocomplete="off"
              @click="showPicker = true"
            />
            <van-popup v-model="showPicker" position="bottom">
              <van-datetime-picker
                v-model="currentDate"
                type="date"
                title="选择年月日"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="onConfirm"
                @cancel="showPicker = false"
              />
            </van-popup>
            <van-field
              name="timeId"
              v-model.trim="form.timeId"
              label="时间段"
              @focus="preKey"
              placeholder="请点击选择"
              autocomplete="off"
              @click="timeshowPicker = true"
            />
            <van-popup
              v-model="timeshowPicker"
              round
              position="bottom"
              @open="opentimedialog"
            >
              <!-- <van-picker
                show-toolbar
                value-key="label"
                :columns="columns"
                @confirm="timeConfirm"
                @cancel="timeshowPicker = false"
              /> -->
              <div class="timeslot">
                <div
                  v-for="(item, index) in timelist"
                  :key="index"
                  class="timeItem"
                  :style="{
                    backgroundColor:
                      item.selectFlag === 'Y' ? '#1a97e7' : '#f1f1f1',
                    color: item.selectFlag === 'Y' ? '#ffffff' : '#666666',
                  }"
                  @click="
                    item.selectFlag === 'Y' &&
                      timeConfirm(item.id, item.startSlot, item.endSlot)
                  "
                >
                  <div class="timetop">
                    {{ item.startSlot + "~" + item.endSlot }}
                    <span
                      v-if="item.selectFlag === 'Y'"
                      :class="{ 'green-text': item.selectFlag === 'Y' }"
                      >(可选)</span
                    >
                    <span
                      v-else
                      :class="{ 'graw-text': item.selectFlag === 'N' }"
                      >(不可选)</span
                    >
                  </div>
                  <div class="timebottom">
                    剩余可预约<span
                      :class="{ 'red-text': item.selectFlag === 'Y' }"
                      >{{ item.syCount }}</span
                    >件
                  </div>
                </div>
              </div>
            </van-popup>
            <!-- <van-field
              v-model.trim="form.sendChannel"
              name="sendChannel"
              label="送货渠道"
              placeholder="请输入送货渠道"
              autocomplete="off"
            /> -->

            <van-field
              name="goodsType"
              v-model.trim="form.goodsType"
              label="货物类型"
              @focus="preKey"
              placeholder="请点击选择"
              autocomplete="off"
              @click="goodsTypePicker = true"
            />
            <van-popup v-model="goodsTypePicker" position="bottom">
              <van-picker
                show-toolbar
                value-key="label"
                :columns="goodsColumns"
                @confirm="goodsConfirm"
                @cancel="goodsTypePicker = false"
              >
              </van-picker>
            </van-popup>
          </div>
          <div class="Stashinfo">
            <div class="title"><span>仓库信息</span><span>(必填)</span></div>
            <van-field
              name="warehouse"
              v-model.trim="form.warehouse"
              label="仓库"
              @focus="preKey"
              placeholder="请点击选择"
              autocomplete="off"
              @click="stashPicker = true"
            />
            <van-popup v-model="stashPicker" position="bottom">
              <van-picker
                show-toolbar
                value-key="label"
                :columns="stashColumns"
                @confirm="stashConfirm"
                @cancel="stashPicker = false"
              />
            </van-popup>
            <div class="Remain">
              <van-icon name="label-o" />
              <span class="textRemain"
                >当日全天剩余收货容量<span>{{ overNumber }}</span
                >件</span
              >
            </div>
            <div class="location">
              <van-icon name="location-o" />
              <span class="locationtext"
                >陕西省西安市未央区陕西数字医药产业园</span
              >
              <i class="el-icon-document-copy" @click="copyText"></i>
            </div>
          </div>
          <div class="imgUpload">
            <div class="title">
              <span>上传货物单据</span><span>(必填)</span>
            </div>
            <!-- <van-uploader
              v-model="fileList"
              :before-delete="handleDelete"
              :after-read="handleUpload"
              :before-read="beforeRead"
              multiple
              :max-count="5"
              preview-size="100px"
            /> -->
          </div>
          <!-- <div class="otherInfo">
            <div class="title"><span>其他信息</span></div>
            <van-field
              v-model.trim="form.identify"
              name="identify"
              label="身份证号"
              placeholder="请输入身份证号"
              autocomplete="off"
            />
            <van-field
              v-model.trim="form.remark"
              name="remark"
              label="备注"
              placeholder="备注"
              autocomplete="off"
            />
          </div> -->
          <div style="margin: 16px">
            <van-button round block type="info" native-type="submit"
              >提交</van-button
            >
          </div>
        </van-form>
      </div>
    </div>
  </div>
</template>

<script>
import carPlateKeyboard from "@/components/Keyw/car-plate-keyboard";
import { getselectOverCount, ExecCount } from "@/api/system/reservation";
import { addReservation, timeList } from "@/api/system/reservation";

import { mapGetters } from "vuex";
export default {
  components: {
    carPlateKeyboard,
  },
  dicts: ["goods_type", "time_slot", "logistics_type"],
  data() {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    return {
      form: {
        // 车牌号
        carNumber: null,
        // 姓名
        driverName: null,
        //   身份证号
        // identify: "",
        // 备注
        // remark: "",
        // 送货渠道
        sendChannel: null,
        // 物流类型
        logisticsType: null,
        // 送货单数
        sendOrder: null,
        // 年月日
        sendDate: new Date().toISOString().split("T")[0],
        // 件数
        sendCount: null,
        // 时间区间
        timeId: null,
        // 货物类型
        goodsType: null,
        // 仓库类型
        warehouse: "普药",
      },
      // 身份证号
      // identify: "",
      // 备注
      // remark: "",
      // 车牌号
      // keyborad: "",
      // 送货渠道
      sendChannelPicker: false,
      sendChannelColumns: [],
      // 物流类型
      logisticsColumns: [],
      logisticsTypePicker: false,
      // path: "",
      // 送货单数
      // single: "",
      currentDate: new Date(),
      minDate: new Date(),
      maxDate: tomorrow,
      // 年月日
      // dateValue: "",
      showPicker: false,
      // 送货单数键盘
      sendOrderKeyBorad: false,
      // 送货件数
      // piece: "",
      showKeyBorad: false,
      // 时间区间
      // timevalue: "",
      columns: [],
      timeshowPicker: false,
      // 货物类型
      // goodsType: "",
      goodsTypePicker: false,
      goodsColumns: [],
      // 仓库
      // stashType: "数字仓",
      stashPicker: false,
      stashColumns: [],
      // 剩余数量
      overNumber: null,
      // 货物类型传给后端的id
      goodsvalue: null,
      // 仓库传给后端
      stashvalue: null,
      // 送货渠道
      sendChannelValue: null,
      // 物流类型
      logisticsValue: null,
      // 时区
      timeValue: null,
      goods: [],
      timelist: [],
      execNum: "",
    };
  },
  watch: {
    // licensePlate(newValue,ov) {
    //   console.log(678, newValue);
    //   console.log(679, ov);
    // },
    "form.sendCount": function (newValue, oldValue) {
      console.log(newValue, oldValue);
      if (newValue !== oldValue) {
        this.form.timeId = "";
      }
    },
    "form.sendDate": function (newsendDateValue, oldsendDateValue) {
      console.log(newsendDateValue, oldsendDateValue);
      if (newsendDateValue !== oldsendDateValue) {
        this.form.timeId = "";
      }
    },
    sendChannelValue(newsendChannelValue, oldsendChannelValue) {
      console.log(newsendChannelValue, oldsendChannelValue);
      if (newsendChannelValue !== oldsendChannelValue) {
        this.form.timeId = "";
      }
    },
    logisticsValue(newlogisticsTypeValue, oldlogisticsTypeValue) {
      console.log(newlogisticsTypeValue, oldlogisticsTypeValue);
      if (newlogisticsTypeValue !== oldlogisticsTypeValue) {
        this.form.timeId = "";
      }
    },
  },
  mounted() {
    // this.getList();
    this.execCountlist();
    this.getOvernumber();
    this.getDicts("goods_type").then((response) => {
      console.log(response.data);
      response.data.forEach((item) => {
        this.goodsColumns.push({
          value: item.dictValue,
          label: item.dictLabel,
        });
      });
      console.log(this.goodsColumns);
    });
    this.getDicts("time_slot").then((response) => {
      response.data.forEach((item) => {
        this.columns.push({
          value: item.dictValue,
          label: item.dictLabel,
        });
      });
    });
    this.getDicts("warehouse").then((response) => {
      response.data.forEach((item) => {
        this.stashColumns.push({
          value: item.dictValue,
          label: item.dictLabel,
        });
      });
    });
    this.getDicts("send_channel").then((response) => {
      response.data.forEach((item) => {
        this.sendChannelColumns.push({
          value: item.dictValue,
          label: item.dictLabel,
        });
      });
    });
    // 物流类型
    this.getDicts("logistics_type").then((response) => {
      response.data.forEach((item) => {
        this.logisticsColumns.push({
          value: item.dictValue,
          label: item.dictLabel,
        });
      });
    });
  },
  computed: {
    ...mapGetters(["driver"]),
  },
  methods: {
    // 送货未履约次数
    execCountlist() {
      ExecCount({ phone: this.driver }).then((res) => {
        this.execNum = res.msg;
      });
    },
    // 输入送货单数失去焦点
    handleSendOrderKeyBorad() {
      this.sendOrderKeyBorad = false;
    },
    // 输入件数失去焦点
    handleshowKeyBorad() {
      // 键盘关闭
      this.showKeyBorad = false;
      if (this.form.sendCount > this.overNumber) {
        this.$toast.fail("输入件数大于当日全天剩余收货数量");
      }
    },
    // 剩余数量
    // getOvernumber() {
    //   getselectOverCount({ setDate: this.form.sendDate }).then((res) => {
    //     this.overNumber = res.data;
    //     console.log(res);
    //   });
    // },
    /** 查询预约管理列表 */
    // getList() {
    //   this.loading = true;
    //   listReservation(this.queryParams).then((response) => {
    //     this.reservationList = response.rows;
    //     this.total = response.total;
    //     this.loading = false;
    //   });
    // },
    async getOvernumber() {
      // getselectOverCount({ setDate: this.form.sendDate }).then((res) => {
      //   this.overNumber = res.data;
      //   console.log(res);
      // });
      const res = await getselectOverCount({ setDate: this.form.sendDate });
      this.overNumber = res.data;
    },
    // 禁止软键盘弹出
    preKey() {
      document.activeElement.blur();
    },
    // 返回
    onClickLeft() {},
    // 时间区间
    // timeConfirm(time) {
    //   this.form.timeSlot = time.label;
    //   this.timeValue = time.value;
    //   this.timeshowPicker = false;
    // },
    timeConfirm(id, starttime, endtime) {
      this.form.timeId = starttime + "~" + endtime;
      this.timeValue = id;
      this.timeshowPicker = false;
    },
    // 打开时间区间弹窗触发
    opentimedialog() {
      if (!this.form.sendCount) {
        this.$toast("请输入送货件数");
      } else if (!this.form.sendDate) {
        this.$toast("请输入预约日期");
      } else if (!this.form.sendChannel) {
        this.$toast("请输入送货渠道");
      } else if (this.sendChannelValue == "1" && !this.form.logisticsType) {
        this.$toast("请输入物流类型");
      } else {
        console.log(111, this.form.sendCount, this.form.sendDate);
        timeList({
          sendCount: this.form.sendCount,
          sendDate: this.form.sendDate,
          sendChannel: this.sendChannelValue,
          logisticsType: this.logisticsValue,
        }).then((res) => {
          this.timelist = res.data;
        });
        // console.log("送货件数", this.form.sendCount, this.form.sendDate);
      }
    },
    // 送货渠道
    sendChannelConfirm(sendChanneltype) {
      this.form.sendChannel = sendChanneltype.label;
      this.sendChannelValue = sendChanneltype.value;
      this.sendChannelPicker = false;
    },
    // 物流类型
    logisticsConfirm(logisticsType) {
      this.form.logisticsType = logisticsType.label;
      this.logisticsValue = logisticsType.value;
      this.logisticsTypePicker = false;
    },
    // 货物类型
    goodsConfirm(good) {
      this.form.goodsType = good.label;
      this.goodsvalue = good.value;
      this.goodsTypePicker = false;
    },
    // 仓库类型
    stashConfirm(stash) {
      this.form.warehouse = stash.label;
      this.stashvalue = stash.value;
      this.stashPicker = false;
    },
    onConfirm(date) {
      this.form.sendDate = `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
      this.getOvernumber();
      this.showPicker = false;
    },
    carSubmit(value) {
      // console.log(1111, value);
      this.form.carNumber = value;
    },
    // onPlateNumberInput(plateNumber) {
    //   // debugger
    // // 在这里处理用户输入的车牌号
    // console.log("车牌号",plateNumber);
    // },
    copyText() {
      const addresstext = document.querySelector(".locationtext");
      // 创建一个临时的textarea元素
      var tempInput = document.createElement("textarea");
      tempInput.value = addresstext.innerText;
      // 添加到DOM中
      document.body.appendChild(tempInput);
      // 选中文本
      tempInput.select();
      tempInput.setSelectionRange(0, 99999);
      // 执行复制命令
      document.execCommand("copy");
      // navigator.clipboard.writeText(tempInput.value).then(()=>{
      //     this.$toast.success("已成功复制至剪贴板");
      // })
      // 移除临时元素
      document.body.removeChild(tempInput);
      // 提示用户复制成功
      this.$toast.success("已成功复制至剪贴板");
    },
    onSubmit(values) {
      console.log(this.form);
      values.goodsType = this.goodsvalue;
      values.warehouse = "0" || this.stashvalue;
      values.sendChannel = this.sendChannelValue;
      values.logisticsType = this.logisticsValue;
      values.timeId = this.timeValue;
      values.phone = this.driver;
      // console.log("submit", values);
      // console.log("sendChannel", values.sendChannel);
      if (
        this.form.carNumber.length == 0 ||
        this.form.sendChannel.length == 0 ||
        this.form.sendOrder.length == 0 ||
        this.form.sendDate.length == 0 ||
        (values.sendChannel == "1" && this.form.logisticsType.length == 0) ||
        this.form.sendCount.length == 0 ||
        this.form.timeId.length == 0 ||
        this.form.goodsType.length == 0 ||
        this.form.warehouse.length == 0 ||
        this.form.driverName.length == 0
      ) {
        this.$toast("请填写完整信息");
      } else if (this.form.sendCount > this.overNumber) {
        this.$toast("输入件数应小于剩余数量");
      } else {
        addReservation(values).then((response) => {
          if (response.data.returnCode == "1") {
            this.$toast.success(response.data.returnMsg);
          } else if (response.data.returnCode == "2") {
            this.$toast.success(response.data.returnMsg);
          } else if (response.data.returnCode == "0") {
            this.$toast.success(response.data.returnMsg);
            this.$router.push({ path: "/reservation" });
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::-webkit-scrollbar {
  display: none;
}
::v-deep .data-show .data-show-block {
  font-size: 14px;
}
.create-reset {
  overflow-y: auto;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  background-color: #f8f8f8;
  .item {
    display: flex;
    justify-content: center;
    flex-direction: column;
    padding: 15px;
    .resetButton {
      width: 100%;
      background: #fff;
      border-radius: 6px;
      height: 45px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      padding: 0 20px;
      position: relative;
      .van-icon-manager-o:before {
        color: #59baff;
        font-size: 18px;
        font-weight: 700;
      }
      .text {
        color: #000000;
        font-weight: 700;
        margin-left: 10px;
      }
      .isfail {
        position: absolute;
        right: 10px;
        width: 30px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        border-radius: 50%;
        background: #ff6868;
        color: #f7f5f5;
      }
    }
    .info {
      margin-top: 15px;
      width: 100%;
      min-height: 400px;
      .box1 {
        border-radius: 6px;
        background: #fff;
        width: 100%;
        min-height: 390px;
        .title {
          font-size: 14px;
          padding: 15px 0 8px 16px;
          span:nth-child(1) {
            font-weight: 700;
          }
          span:nth-child(2) {
            color: #ff6868;
            margin-left: 10px;
          }
        }
        .timeslot {
          display: flex;
          justify-content: space-between;
          align-items: center;
          flex-wrap: wrap;
          min-height: 200px;
          padding: 30px 20px 50px 20px;
          .timeItem {
            width: 48%;
            height: 50px;
            border-radius: 8px;
            // border: 1px solid #ababac;
            text-align: center;
            line-height: 1.7;
            margin-bottom: 10px;
            // color: #ffffff;
            .timetop {
              font-size: 14px;
              span {
                font-size: 10px;
              }
              .green-text {
                color: #65fa97;
              }
              .graw-text {
                color: #afb0b1;
              }
            }
            .timebottom {
              font-size: 14px;
              .red-text {
                color: #00ff0d;
              }
            }
          }
        }
      }
      .Stashinfo {
        font-size: 14px;
        margin-top: 15px;
        width: 100%;
        background: #fff;
        border-radius: 6px;
        height: 180px;
        .title {
          padding: 15px 0 8px 16px;
          span:nth-child(1) {
            font-weight: 700;
          }
          span:nth-child(2) {
            color: #ff6868;
            margin-left: 10px;
          }
        }
        .Remain {
          display: flex;
          justify-content: flex-start;
          margin: 0px 16px 0 16px;
          padding: 15px 0;
          border-bottom: 1px solid #f7f5f5;
          .van-icon-label-o:before {
            font-weight: 700;
          }
          .textRemain {
            margin-left: 10px;
            color: #646566;
            span {
              color: #000000;
              padding: 0 4px;
            }
          }
        }
        .location {
          display: flex;
          justify-content: flex-start;
          // margin: 12px 16px 0 16px;
          // padding-bottom: 10px;
          margin: 0px 16px 0 16px;
          padding: 15px 0;
          border-bottom: 1px solid #f7f5f5;
          .van-icon-location-o:before {
            font-weight: 700;
          }
          .locationtext {
            margin-left: 10px;
            color: #646566;
            margin-right: 10px;
          }
          .van-icon-arrow:before {
            margin-left: 20px;
          }
        }
      }
      .imgUpload {
          width: 100%;
          margin-top: 20px;
          height: 100px;
          .title {
            padding: 15px 0 8px 16px;
            span:nth-child(1) {
              font-weight: 700;
            }
            span:nth-child(2) {
              color: #ff6868;
              margin-left: 10px;
            }
          }
        }
      .otherInfo {
        margin-top: 15px;
        width: 100%;
        background: #fff;
        border-radius: 6px;
        height: 130px;
        .title {
          font-size: 14px;
          padding: 15px 0 8px 16px;
          span:nth-child(1) {
            font-weight: 700;
          }
          span:nth-child(2) {
            color: #ff6868;
            margin-left: 10px;
          }
        }
      }
    }
  }
}
</style>